package com.foster.eric.sample.weightloss.service;

import static com.foster.eric.sample.weightloss.utils.ConverterUtils.FEMALE_ADJUSTMENT;
import static com.foster.eric.sample.weightloss.utils.ConverterUtils.MALE_ADJUSTMENT;
import static com.foster.eric.sample.weightloss.utils.ConverterUtils.convertInchesToCM;
import static com.foster.eric.sample.weightloss.utils.ConverterUtils.convertPoundsToKg;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Service;

import com.foster.eric.sample.weightloss.form.Gender;
import com.foster.eric.sample.weightloss.form.Measurements;
import com.foster.eric.sample.weightloss.form.Result;
import com.foster.eric.sample.weightloss.form.Schedule;
import com.foster.eric.sample.weightloss.utils.ConverterUtils.Multiplier;


@Service
public class CalculationServiceImpl implements CalculationService {

	private static final double TWO_POUND_WEEKLY_DEFICIT = 1000;
	
	@Override
	public List<Result> calculate(Measurements measurements) {
		
		double bee = this.calculateBEE(measurements);
		 
		int day = 1;
		BigDecimal startingWeight = measurements.getCurrentWeight();
		
		List<Result> results = new ArrayList<Result>();
		results.add( this.createResult(new Date(), day, startingWeight, bee - TWO_POUND_WEEKLY_DEFICIT) );
		
		//while( startingWeight.doubleValue() > measurements.getGoalWeight().doubleValue())
			
		return results;
	}

	private double calculateBEE( Measurements measurements )
	{
		double weightInKg = convertPoundsToKg(measurements.getCurrentWeight().doubleValue());
		double heightInCM = convertInchesToCM(measurements.getHeight());
		
		double formulaAdjustedWeight = Multiplier.weight.getMultiplier(measurements.getGender()) * weightInKg;
		double formulaAdjustedHeight = Multiplier.height.getMultiplier(measurements.getGender()) * heightInCM;
		double formulaAdjustedAge	 = Multiplier.age.getMultiplier(measurements.getGender()) * measurements.getAge();
		double adjustmentForGender = measurements.getGender() == Gender.male ?  MALE_ADJUSTMENT :  FEMALE_ADJUSTMENT;
		double bmr = adjustmentForGender + formulaAdjustedWeight +  formulaAdjustedHeight - formulaAdjustedAge;
			
		return bmr * measurements.getLifestyle().getWeight();
	}
	
	
	
	private Result createResult(Date date, int day, BigDecimal estimatedLoss, double calorieIntake )
	{
		Schedule schedule = new Schedule();
		schedule.setDay(day);
		schedule.setScheduleDate(date);;
		
		Result result = new Result();
		result.setSchedule(schedule);
		result.setCalories(new BigDecimal(calorieIntake));
		result.setEstimatedLoss(estimatedLoss);
		
		return result;
	}
	
}
